/*
 * @Author: zhang ke
 * @Date: 2025-06-21 10:34:10
 * @LastEditors: your name
 * @LastEditTime: 2025-06-28 11:51:31
 * @Description: 封装axios
 * @FilePath: \vue3-admin\src\utils\request.ts
 */
import axios from 'axios'

import { ElMessage } from 'element-plus'
import useUserStore  from '@/store/modules/user'
const base = import.meta.env.VITE_APP_API // 接口地址

const request= axios.create({
  baseURL: base,
  timeout: 60000, // 设置超时时间 
})
//请求拦截器
request.interceptors.request.use(
    (config)=>{
       let userStore = useUserStore()
        if(userStore.token || localStorage.getItem('TOKEN')){
             config.headers.token = userStore.token || localStorage.getItem('TOKEN')// 设置token
        }       
        return config
    },
    (error) => {
    return Promise.reject(error)
  },
)
// 响应拦截器
request.interceptors.response.use(
    (response)=>{
        if(response.status == 200){
            return Promise.resolve(response.data)
        }else{
            return Promise.reject(response.data)
        }
    },
    (error) =>{
        let message = ''
        const status = error.response.status
        switch(status){
            case 401:
                message = '未登录'
                break
            case 404:
                message = '网络请求不存在'
                break
            case 500:
                message = '服务器出现错误'
                break
            default:
                message = error.response.data.message
        }
        ElMessage({
            type:'error',
            message,
        })
        return Promise.reject(error)
    }
)

export default request

